package com.amado.course42Socket.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wangyulong
 * @version 1.5.0
 * @date 2020/3/7 10:29
 */
public class HttpServerDemo {
    // 两个常量
    private static final String CRLF = "\r\n";
    private static final String BLANK = " ";

    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(80);
        long count = 0;
        while (true) {
            Socket socket = server.accept(); // 获取客户端连接
            System.out.println("第["+ (++count) +"]个客户端！ip为：" + socket.getInetAddress().getHostAddress() + " 访问时间： " + new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date()) );
            new Thread( new Server(socket) ).start();
        }

    }
    /**
     * server
     *
     * @author snow
     *
     */
    static class Server implements Runnable {

        // 两个常量
        private static final String CRLF = "\r\n";
        private static final String BLANK = " ";

        private Socket server;
        private String path;

        public Server(Socket server) {
            this.server = server;
            System.out.println( "客户端：" + this.server.getInetAddress().getHostName() +" 的请求头文件为：" );
            System.out.println( getData() );
        }

        private String getData() {
            try {
                BufferedInputStream bis = new BufferedInputStream( this.server.getInputStream() );

                byte [] data = new byte[2048];
                int len = bis.read(data);
                String msg = new String(data,0,len);

                int start = msg.indexOf("/");
                int end = msg.indexOf("HTTP");

                this.path = msg.substring((start+1), end).trim();
                return msg;
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }

        private void sendData() {
            try {
                BufferedOutputStream bos = new BufferedOutputStream(this.server.getOutputStream());

                String suffix = path.substring(path.lastIndexOf(".")+1);

                File file = new File(path);
                System.out.println(file.getAbsolutePath());
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                StringBuffer sb = new StringBuffer();
                // http 协议版本，状态码，描述
                sb.append("HTTP/1.1").append(BLANK).append(520).append(BLANK).append("love").append(CRLF);
                // 响应头
                sb.append("Server:v  Server/12.19.06.14").append(CRLF).append("Date:").append(new Date()).append(CRLF)
                ;
                if( "jpg".equals(suffix)) {
                    sb.append("Content-type:image/jpg").append(CRLF);
                }else if("png".equals(suffix)) {
                    sb.append("Content-type:image/png").append(CRLF);
                }else if("gif".equals(suffix)) {
                    sb.append("Content-type:image/gif").append(CRLF);
                }else if("html".equals(suffix)) {
                    sb.append("Content-type:text/html").append(CRLF);
                }else if("css".equals(suffix)) {
                    sb.append("Content-type:text/css").append(CRLF);
                }else if("js".equals(suffix)) {
                    sb.append("Content-type:application/x-javascript").append(CRLF);
                }else {
                    sb.append("Content-type:application/octet-stream").append(CRLF);
                }

                sb.append("Connection:keep-alive").append(CRLF);
                // 正文长度：内容
                sb.append("Content-Length:").append(file.length()).append(CRLF).append(CRLF);

                bos.write(sb.toString().getBytes());

                byte [] flush = new byte[1024*1024];
                int len = bis.read(flush);
//			while( (len=bis.read(flush)) != -1 ){
                bos.write(flush, 0, len);
                System.out.println( "读取成功！==>" + path );
//			}
                bos.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        @Override
        public void run() {
            sendData();
        }
    }
}
